package com.szsh.aiot.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class UrlUtils {

    /**
     * httpUrl添加参数<br>
     * 添加一个参数
     * @param httpUrl http/https地址
     * @param name    参数名称
     * @param value   参数值
     * @return 添加参数后的http/https地址
     */
    public static String httpUrlAddParam(String httpUrl, String name, Object value) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(name, value);
        return httpUrlAddParam(httpUrl, hashMap);
    }

    /**
     * httpUrl添加参数
     * @param httpUrl http/https地址
     * @param params  添加的参数
     * @return 添加参数后的http/https地址
     */
    public static String httpUrlAddParam(String httpUrl, Map<String, Object> params) {
        if (null == params || params.isEmpty()) {
            return httpUrl;
        }
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(httpUrl);

        String fragment = uriComponentsBuilder.build().getFragment();
        if (StringUtils.isNotBlank(fragment)) {
            // url 有 # 号
            // 参数 加在 # 后面
            UriComponentsBuilder fragmentUriComponentsBuilder = UriComponentsBuilder.fromPath(fragment);
            params.forEach(fragmentUriComponentsBuilder::queryParam);

            // 修改 # 后面 参数
            uriComponentsBuilder.fragment(fragmentUriComponentsBuilder.build().toUriString());
        }
        // 设置参数
        params.forEach(uriComponentsBuilder::queryParam);

        return uriComponentsBuilder.build().toUriString();
    }

    /**
     * url是否需要编码<br>
     * 有 ? 进行编码
     * @param url 要编码的url
     * @return 编码后的url
     */
    public static String urlNeedEncoder(String url) {
        if (StringUtils.isBlank(url)) {
            return "";
        }
        if (url.contains("?")) {
            // 有 ? 需要编码
            return urlEncoder(url);
        }
        return url;
    }

    /**
     * url编码
     * @param url 要编码的url
     * @return 编码后的url
     */
    public static String urlEncoder(String url) {
        if (StringUtils.isBlank(url)) {
            return "";
        }
        try {
            return URLEncoder.encode(url, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            return url;
        }
    }
}
